﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace Project_1
{
    /// <summary>
    /// 1.8 前台线程和后台线程
    /// </summary>
    public class Unit_1_08
    {
        /*
         * 程序会等待所有前台线程执行完才会结束，
         * 而不会等待后台线程
         */
        public static void Go()
        {
            //声明前台线程
            var sampleForeground =new ThreadSample(8);
            //声明后台线程
            var sampleBackground = new ThreadSample(8);

            var threadOne = new Thread(sampleForeground.CountNumbers);
            threadOne.Name = "One前台线程";
            var threadTwo=new Thread(sampleBackground.CountNumbers);

            threadTwo.Name = "Two后台线程";
            threadTwo.IsBackground = true;

            threadOne.Start();
            Sleep(TimeSpan.FromSeconds(3));
            threadTwo.Start();
        }

        class ThreadSample
        {
            private readonly int _iterations;//迭代次数

            public ThreadSample(int iterations)
            {
                _iterations = iterations;
            }

            public void CountNumbers()
            {
                for (int i = 0; i < _iterations; i++)
                {
                    Sleep(TimeSpan.FromSeconds(0.5));
                    WriteLine($"{CurrentThread.Name} i:{i}");
                }
            }
        }

    }
}
